package com.catfairy.user.listener;

import com.catfairy.common.utils.JSONUtil;
import com.catfairy.common.utils.Mail;
import com.catfairy.user.common.dataobject.UserInfo;
import com.catfairy.user.constant.Constants;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author 猫大仙
 */
@Slf4j
@Component
public class UserQueueListener {
    @Autowired
    private Mail mail;

//    @RabbitListener(queues = Constants.USER_QUEUE_NAME)
//    public void handler(Message message, Channel channel) throws IOException {
//        long deliveryTag = message.getMessageProperties().getDeliveryTag();
//        try{
//            String body = new String(message.getBody());
//            log.info("收到消息:{}",body);
//            channel.basicAck(deliveryTag,true);
//        } catch (Exception e) {
//            channel.basicNack(deliveryTag,true,true);
//            log.error("发送失败,e:",e);
//        }
//    }
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = Constants.USER_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(value = Constants.USER_EXCHANGE_NAME,type = ExchangeTypes.FANOUT)
    ))
    public void handler(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try{
            String body = new String(message.getBody());
            log.info("收到消息:{}",body);
            UserInfo userInfo = JSONUtil.parseJson(body, UserInfo.class);
            mail.send(userInfo.getEmail(),"注册成功","欢迎使用博客社区");
            channel.basicAck(deliveryTag,true);
        } catch (Exception e) {
            channel.basicNack(deliveryTag,true,true);
            log.error("发送失败,e:",e);
        }
    }

}
